package com.bookstore.servlet.admin;


import com.bookstore.data.DataConst;
import com.bookstore.entity.Product;
import com.bookstore.service.ProductService;
import com.bookstore.service.impl.ProductServiceImpl;
import com.bookstore.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.List;

@MultipartConfig
@WebServlet("/admin/product.do")
public class ProductServlet extends BaseServlet {
    ProductService productService = new ProductServiceImpl();

    public void queryAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = productService.queryAll();
        request.setAttribute("products", products);
        request.getRequestDispatcher("/admin/product_list.jsp").forward(request, response);
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long productId = Long.valueOf(request.getParameter("productId"));
        int result = productService.delete(productId);
        //更新结果 传到前端去
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(String.valueOf(result));
//        response.sendRedirect("product.do?action=queryAll");
    }

    public void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //Servlet3.0中新引入的方法，用来处理multipart/form-data类型编码的表单
        //name="imgUrl" 对应前端表单的参数
        Part part = request.getPart("imgUrl");
        //获取HTTP头信息headerInfo=（form-data; name="imgUrl" filename="文件名"）
        String headerInfo = part.getHeader("content-disposition");
        //从HTTP头信息中获取文件名fileName=（文件名）
        String fileName = headerInfo.substring(headerInfo.lastIndexOf("=") + 2, headerInfo.length() - 1);
        //获得存储上传文件的文件夹路径
        //获得存储上传文件的完整路径（文件夹路径+文件名）
        //文件夹位置固定，按照当前毫秒值+文件后缀名的方式生成文件名
        long timeMills = System.currentTimeMillis();
        //1.2.jpg ==> "1"  "2"  "jpg"
        String[] split = fileName.split("\\.");
        String s = split[split.length - 1];
        //获取当前上传文件的后缀名
        String newFileName = new StringBuilder(s).insert(0, ".").insert(0, timeMills).toString();
        String fileSavingPath = DataConst.FILE_UPLOAD_DIRECTORY + newFileName;
        //如果存储上传文件的文件夹不存在，则创建文件夹
        File f = new File(DataConst.FILE_UPLOAD_DIRECTORY);
        if (!f.exists()) {
            f.mkdirs();
        }
        //将上传的文件内容写入服务器文件中
        part.write(fileSavingPath);
        String productName = new String(request.getParameter("productName").getBytes("iso-8859-1"), "UTF-8");
        Double price = Double.valueOf(new String(request.getParameter("price").getBytes("iso-8859-1"), "UTF-8"));
        String category = new String(request.getParameter("category").getBytes("iso-8859-1"), "UTF-8");
        Integer pNum = Integer.valueOf(new String(request.getParameter("pNum").getBytes("iso-8859-1"), "UTF-8"));
        String description = new String(request.getParameter("description").getBytes("iso-8859-1"), "UTF-8");
        int result = productService.insert(new Product(null, productName, price, category, pNum, newFileName, description));
        response.sendRedirect("product.do?action=queryAll");
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long id = Long.valueOf(request.getParameter("id").trim());
        String productName = request.getParameter("productName");
        Double price = Double.valueOf(request.getParameter("price").trim());
        String category = request.getParameter("category");
        Integer pNum = Integer.valueOf(request.getParameter("pNum"));
        String imgUrl = request.getParameter("imgUrl");
        String description = request.getParameter("description");
        int result = productService.update(new Product(id, productName, price, category, pNum, imgUrl, description));
        response.sendRedirect("product.do?action=queryAll");
    }
}
